import tools from '../utils/tools.js'

const request = async (url, method, data = {}) => {
	try {
		return new Promise((reslove, reject) => {
			uni.request({
				url: 'https://api.xiaoshengkeji.cn' + url,
				method: method || 'GET',
				header: {
					Accept: "application/json",
					Authorization: uni.getStorageSync('token') ? "Bearer " + uni.getStorageSync(
						'token') : ''
				},
				timeout: 10000,
				// data: data || {},
				data: {
					cid: uni.getStorageSync('userInfo').cid || null,
					user_id: uni.getStorageSync('userInfo').uid || null,
					...data
				},
				success: (successData) => {
					// console.log('successData',JSON.stringify(successData.data));
					if (successData.data.code == -1) {
						uni.showToast({
							title: "登录已过期，请重新登入~",
							icon: "none",
							duration: 1500,
							success() {
								setTimeout(() => {
									try {
										uni.clearStorageSync();
									} catch (e) {
										//TODO handle the exception
									}
									tools.reLaunchTo('login/login')
								}, 500);
							}
						});
						// reslove(successData.data)
					} else if (successData.statusCode == 200) {
						reslove(successData.data)
					} else if (successData.data.code === 1) {
						reslove(successData.data)
					} else {
						console.log('请求失败');
						tools.toast(successData.data.msg)
					}
					// if(successData.data.code === 200) {
					// 	reslove(successData)
					// } else if(successData.data.code === 401) {
					//   uni.showToast({
					//     title: "请登录后操作~",
					//     icon: "none",
					//     duration: 500,
					//     success() {
					//       setTimeout(() => {
					//         try {
					//           uni.clearStorageSync();
					//         } catch (e) {
					//           //TODO handle the exception
					//         }
					//         uni.reLaunch({
					//           url: "/pages/login/index"
					//         });
					//       }, 500);
					//     }
					//   });
					//   return;
					// } else {
					// 	reslove(successData)
					// }
				},
				fail: (msg) => {
					uni.showToast({
						title: '网络连接失败，请稍后重试',
						icon: 'none'
					})
					reject(msg)
				}
			})
		})
	} catch (e) {
		//TODO handle the exception
	}

}

export default request